package cn.well.cloud.quartz.core.runner;


import cn.well.cloud.quartz.core.model.ScheduleJob;
import cn.well.cloud.quartz.core.task.TaskUtils;
import cn.well.cloud.quartz.modular.model.Timetask;
import cn.well.cloud.quartz.modular.service.ITimetaskService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 启动定时任务
 * wison
 * 下午9:02:24
 */

@Component
@Order(value = 1)
public class QuartzApplicationRunner implements ApplicationRunner {
        
    @Autowired
    private ITimetaskService timetaskService;
    
    @Autowired
    private TaskUtils taskUtils;

    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("定时任务启动...");
        // 这里从数据库中获取任务信息数据
        QueryWrapper<Timetask> queryWrapper =new QueryWrapper<Timetask>();
        queryWrapper.eq("job_status", "1");// 已发布的定时任务
        List<Timetask> list = timetaskService.list(queryWrapper);
        List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
        for (Timetask timetask : list) {
          ScheduleJob job1 = new ScheduleJob();
          job1.setJobId(timetask.getTaskId().toString());
          job1.setJobGroup(timetask.getGroupName()); // 任务组
          job1.setJobName(timetask.getName());// 任务名称
          job1.setJobStatus(timetask.getJobStatus()); // 任务发布状态
          job1.setIsConcurrent(timetask.getConcurrent().toString()); // 运行状态
          job1.setCronExpression(timetask.getCron());
          job1.setBeanClass(timetask.getBeanName());// 一个以所给名字注册的bean的实例
          job1.setMethodName(timetask.getMethodName());
          job1.setJobData(timetask.getJobData()); // 参数
          jobList.add(job1);
        }

        for (ScheduleJob job : jobList) {
          try {
              taskUtils.addJob(job);
          } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
    }
    
    
   

}

